package com.itheima.dianming.config;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dianming.mapper.StuMapper;
import com.itheima.dianming.pojo.domain.Stu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class SpringSecurityUserService implements UserDetailsService {

    @Autowired
    private StuMapper stuMapper;

    //根据用户名查询数据库获取用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Stu> qw= new LambdaQueryWrapper<>();
        qw.eq(Stu::getNumber,username);
        qw.or().eq(Stu::getUsername,username);
        List<Stu> stus = stuMapper.selectList(qw);
        if(stus == null || stus.size() == 0 ){
            //用户名不存在
            return null;
        }
        if(stus.size() > 1){
            throw new UsernameNotFoundException("用户名重复拉，请使用学号登录！");
        }
        List<GrantedAuthority> list = new ArrayList<>();
        if(username.equals("admin")){
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        org.springframework.security.core.userdetails.User
                securityUser =
                new User(stus.get(0).getNumber(),stus.get(0).getPassword(),list);
        return securityUser;
    }
}
